(function(angular) {
	'use strict';
	angular.module('fs.waf').controller('cda.intindex.uploadController', uploadController);
	uploadController.$inject = [ '$scope', '$q', 'Constants', 'gridService', 'modalService', 'layoutConfig', 'validatorConfig', 'authService',
			'intindexService' ];
	function uploadController($scope, $q, Constants, gridService, modalService, layoutConfig, validatorConfig, authService, intindexService) {
		var ctrl = this, log = $scope.loggerFactory.getLogger("intindexUpload");
		var intindexListInfo = $scope.$stateParams.params;
		ctrl.layoutConfig = layoutConfig;
		ctrl.validatorConfig = validatorConfig;
		ctrl.intindexList = {};
		
		ctrl.init = function() {
			authService.uploadInit(intindexListInfo).then(function(response) {
				ctrl.intindexList = response.data || intindexListInfo;
				ctrl.intindexList= response.data;
				ctrl.intindexList.formatSample ='CCY,	Index Name,	Tenor,	Effective Date,	Rate\n'+
												'IDR,	POF,	30,	2015-02-16,	9.59\n'+
												'IDR,	POF,	90,	2015-02-16,	9.84\n'+
												'IDR,	INVF,	30,	2015-02-16,	8.99\n';
				ctrl.intindexList.formatDesc ='rateIndexes defines Site and default Effective Date in YYYY-MM-DD format.\n'+
											  'index defines Index Name, Currency, Rate and optional Effective Date in YYYY-MM-DD format.';
			});
		};

		ctrl.upload = function() {
			if (!ctrl.intindexList.uploadInfo || ctrl.intindexList.uploadInfo.length == 0) {
				modalService.openErrorDialogs({
					'messages' : [ 'title.dialogs.intindex.choose.file']
				});
				return;
			}
			var fileName = ctrl.intindexList.uploadInfo[0].docFileName;
			ctrl.intindexList.docId = ctrl.intindexList.uploadInfo[0].docId;
			var position = fileName.lastIndexOf(".");
			var fmt = fileName.substring(position + 1, fileName.length);
			if (fmt.toLowerCase() != "csv" && fmt.toLowerCase() != "xml") {
				modalService.openErrorDialogs({
					'messages' : [ 'title.dialogs.intindex.must.csv']
				});         
			} else {					
				return authService.upload(ctrl.intindexList).then(uploadSuccessful, uploadFailed);
			}
		};

		function uploadSuccessful(response) {
			modalService.openAcknowledgeDialogs({
				'messages' : [ 'title.dialog.successful.approve' ],
				'btnCallback' : {
					'close' : function() {
						$scope.go('cda.workflow.wfSetup.list');
					}
				},
				'redirections' : [ {
					'name' : 'title.infobar.workflow.list',
					'state' : 'cda.workflow.wfSetup.list',
					'params' : {}
				}, {
					'name' : 'title.infobar.intindex.list',
					'state' : 'cda.intindex.list',
					'params' : {}
				}]
			});
		}

		function uploadFailed(response) {
			modalService.openErrorDialogs({
				'messages' : response.error
			});
		}

		
	}
})(angular);
